今天來點開胃菜提供練習~ 還有提供物件導向(OOP)的範例!
def bubble_sort(lst):
for i in range(len(lst) - 1):
for j in range(len(lst) - 1 - i):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
print(bubble_sort([5, 3, 2, 1, 4])) # Output: [1, 2, 3, 4, 5]
def insertion_sort(lst):
for i in range(1, len(lst)):
j = i
while j > 0 and lst[j] < lst[j - 1]:
lst[j], lst[j - 1] = lst[j - 1], lst[j]
j -= 1
return lst
print(insertion_sort([5, 3, 2, 1, 4])) # Output: [1, 2, 3, 4, 5]
def merge_sort(lst):
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = merge_sort(lst[:mid])
right = merge_sort(lst[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
print(merge_sort([5, 3, 2, 1, 4])) # Output: [1, 2, 3, 4, 5]
class BirthdayCard:
def __init__(self, recipient, content, sender):
self.recipient = recipient # 收件人
self.content = content # 卡片內容
self.sender = sender # 寄件人
def send_card(self):
print(f"生日卡片已寄給 {self.recipient},內容:{self.content}")
# 創建一張生日卡片物件
birthday_card = BirthdayCard("五條悟", "祝你生日快樂!", "虎杖")
# 發送生日卡片
birthday_card.send_card()
# 生日卡片已寄給 五條悟,內容:祝你生日快樂!
class MyClass:
def __init__(self, value):
self.value = value
def method(self):
print(self.value)
# Create an instance of MyClass
obj = MyClass(10)
# Call the method
obj.method() # Output: 10
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
# Create a new dog object
dog = Dog("Fido", "Labrador")
# Access the object's data
print(dog.name) # Output: "Fido"
print(dog.breed) # Output: "Labrador"
# Call the object's method
dog.bark() # Output: "Woof!"
#Fido
#Labrador
#Woof!
class ClassA:
def __init__(self, value):
self.value = value
def method_a(self):
print("Method A called")
class ClassB:
def __init__(self):
self.obj_a = ClassA(10)
def method_b(self):
print("Method B called")
print(self.obj_a.value) # Access attribute of ClassA
self.obj_a.method_a() # Call method of ClassA
# Create an instance of ClassB
obj_b = ClassB()
# Call method of ClassB
obj_b.method_b()
# Method B called
# 10
# Method A called